Swift.String で regex を用いた置換を行う
半角カナ → 全角カナ
extension String {
/// 半角カナを全角カナに変換
func replacingHalfKatakanaToFull() -> String {
// regex: https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block)
guard let regex = try? NSRegularExpression(pattern: "[ヲ-゚]+") else { return self }
var result = self
let matched = regex.matches(in: self, range: NSRange(location: 0, length: utf16.count))
matched.forEach {
let substring = (result as NSString).substring(with: $0.range)
let transformed = substring.applyingTransform(.fullwidthToHalfwidth, reverse: true)
result = result.replacingOccurrences(of: substring, with: transformed ?? substring)
print(result)
}
return result
}
}
全角英数 → 半角英数
extension String {
/// 全角英数字を半角英数字に変換
func replacingFullAlphanumericToHalf() -> String {
guard let regex = try? NSRegularExpression(pattern: "[0-9a-zA-Z]+") else { return self }
var result = self
let matched = regex.matches(in: self, range: NSRange(location: 0, length: utf16.count))
matched.forEach {
let substring = (result as NSString).substring(with: $0.range)
let transformed = substring.applyingTransform(.fullwidthToHalfwidth, reverse: false)
result = result.replacingOccurrences(of: substring, with: transformed ?? substring)
print(result)
}
return result
}
}
Swift Regex